//
//  OfficeNoticeViewController.swift
//  EduManage
//
//  Created by design02 on 16/12/12.
//  Copyright © 2016年 wsl. All rights reserved.
//

import UIKit

class OfficeNoticeViewController: BaseViewController,UITableViewDelegate,UITableViewDataSource {
    
    var segmentedControl: UISegmentedControl!
    var switchSegment = UISegmentedControl()
    
    var tableView: UITableView!
    
    var mark = "1"
    
    var workArray = NSMutableArray()
    var classArray = NSMutableArray()
    
    let top = 10
    var pageIndex = 1
    
    var modetype: String!
    
    var chart = PDChart()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = "通知公告"

        setupViews()
    }
    func setupViews(){
        
        let array = ["统计汇总","用户阅读"]
        segmentedControl = UISegmentedControl.init(items: array)
        segmentedControl.frame = CGRect(x: 15, y: 74, width: screenW - 30, height: 40)
        segmentedControl.selectedSegmentIndex = 0
        segmentedControl.tintColor = barColor
        segmentedControl.addTarget(self, action: #selector(ClassWorkViewController.selTab), for: UIControlEvents.valueChanged)
        self.view.addSubview(segmentedControl)

        tableView = UITableView.init(frame: CGRect(x: 0, y: segmentedControl.frame.maxY + 10, width: screenW, height: screenH - segmentedControl.frame.maxY - 10))
        tableView.backgroundColor = UIColor.init(hexString: "f6f6f6", alpha: 1)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        self.view.addSubview(tableView)
        setUpRefresh()
    }
    
    func setUpRefresh() {
        if mark == "1" {
            tableView.header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(OfficeNoticeViewController.refresh))
            tableView.footer = nil
            self.tableView.header.beginRefreshing()
            
        }else {
            tableView.header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(OfficeNoticeViewController.refresh))
            tableView.footer = MJRefreshFooter.init(refreshingTarget: self, refreshingAction: #selector(OfficeNoticeViewController.loadMore))
            self.tableView.header.beginRefreshing()
        }
        
    }
    //按用户阅读 - 加载更多
    func loadMore() {
        
        if (reachability?.isReachable())! {
            let user = getUserPojo()
            let url = server + adminofficewebappapi
            pageIndex += 1
            let page: String = String(pageIndex)
            
            let request = requestHeader + "2</t><schid>" + user.schid + "</schid><top>12</top><pageindex>" + page + "</pageindex></channel></rss>"
            
            if getData(url, request: request).count != 0 {
                workArray = getData(url, request: request)
            }
            
            tableView.reloadData()
            
        } else {
            HYLog("网络连接：不可用")
        }
        
        
        tableView.footer.endRefreshing()
    }
    //刷新
    func refresh() {
        
        if (reachability?.isReachable())! {
            
            let user = getUserPojo()
            let url = server + adminofficewebappapi
            
            if mark == "2" {
                
                UIView.animate(withDuration: 1.0, animations: {
                    self.chart.removeFromSuperview()
                    self.switchSegment.removeFromSuperview()
                })
                /**
                 - 用户阅读接口地址：GJ_ModularmentBG.ashx?t=2
                 - 用户阅读参数：
                 
                 XmlNode schidxml = ndoc.SelectSingleNode("//rss/channel/schid");
                 XmlNode topxml = ndoc.SelectSingleNode("//rss/channel/top");
                 XmlNode pageindexxml = ndoc.SelectSingleNode("//rss/channel/pageindex");
                 */
                pageIndex = 1
                let page: String = String(pageIndex)
                let request = requestHeader + "2</t><schid>" + user.schid + "</schid><top>12</top><pageindex>" + page + "</pageindex></channel></rss>"
                
                workArray = getData(url, request: request)
                tableView.separatorStyle = UITableViewCellSeparatorStyle.none
                
                if workArray.count == 0 {
                    TSMessage.showNotification(in: self, title: "温馨提示", subtitle: "暂时还没有通知公告阅读信息、请添加后重试！", image: nil, type: TSMessageNotificationType.warning, duration: 2.0, callback: nil, buttonTitle: "知道了", buttonCallback: nil, at: TSMessageNotificationPosition.top, canBeDismissedByUser: true)
                }
                
            }else if mark == "1" {
                /**
                 - 统计发布数量接口地址：GJ_ModularmentBG.ashx?t=3
                 - 统计发布数量参数：
                 
                 XmlNode schidxml = ndoc.SelectSingleNode("//rss/channel/schid");
                 */
                let request = requestHeader + "3</t><schid>" + user.schid + "</schid></channel></rss>"
                
                classArray =  getData(url, request: request)
                tableView.separatorStyle = UITableViewCellSeparatorStyle.none
                
                setupSwitchBtn()
                
                if switchSegment.selectedSegmentIndex == 0 {
                    
                    self.chart.removeFromSuperview()
                    if !self.tableView.subviews.contains(chart) {
                        
                        let barChart: PDBarChart = OfficeLeaveViewController().getBarChart(classArray)
                        chart = barChart
                        self.tableView.addSubview(chart)
                        
                    }
                    
                    chart.strokeChart()
                    
                }else if switchSegment.selectedSegmentIndex == 1 {
                    
                    self.chart.removeFromSuperview()
                    if !self.tableView.subviews.contains(chart) {
                        
                        let barChart: PDLineChart = OfficeLeaveViewController().getLineChart(classArray)
                        chart = barChart
                        self.tableView.addSubview(chart)
                    }
                    
                    chart.strokeChart()
                    
                    print("显示折线图")
                }
                
            }
            
            tableView.reloadData()
            
        } else {
            let alert = UIAlertView.init(title: "错误提示", message: "似乎已断开与互联网的连接", delegate: nil, cancelButtonTitle: "知道了")
            alert.show()
            
            self.perform(#selector(OfficeNoticeViewController.dimissAlert(alert:)), with: alert, afterDelay: 2.0)
            HYLog("网络连接：不可用")
        }
        
        
        tableView.header.endRefreshing()
    }
    
    func dimissAlert(alert: UIAlertView) {
        alert.dismiss(withClickedButtonIndex: alert.cancelButtonIndex, animated: true)
    }
    /**
     选项切换
     */
    func selTab() {

        let n = segmentedControl.selectedSegmentIndex
        switch n {
        case 0:
            mark = "1"
            setUpRefresh()
            break
        case 1:
            mark = "2"
            setUpRefresh()
            break
        default:
            break
        }
    }
    
    //MARK: - table view delegate and data source
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if mark == "1" {
            return 0
        }else {
            return 60
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if mark == "1" {
            return 0
        }else {
            return workArray.count
        }
        
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if mark == "2" {
            let cellIdentifier = "OfficeClassSendTableViewCellIdentifier";
            
            let cell: OfficeNoticeTableViewCell = OfficeNoticeTableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: cellIdentifier)
            cell.selectionStyle = UITableViewCellSelectionStyle.none;
            if (indexPath as NSIndexPath).row < workArray.count {
                
                let dic = workArray[indexPath.row] as! JSON
                
                let TeaName = dic["TeaName"].stringValue
                let YRead = dic["YRead"].stringValue
                let UNRead = dic["UNRead"].stringValue
                var photo = dic["photo"].stringValue
                
                photo = photo.replacingOccurrences(of: "../..", with: "").replacingOccurrences(of: "../", with: "/view/")
                photo = server + photo
                cell.userTx.sd_setImage(with: URL.init(string: photo), placeholderImage: UIImage.init(named: "touxiangm"))
                
                
                cell.userName.text = "\(TeaName)"
                cell.readLabel.text = "已读: \(YRead)"
                cell.unReadLabel.text = "未读: \(UNRead)"
                
            }
            
            return cell
            
        }else if mark == "1" {
            let cellIdentifier = "OfficeClassSendTableViewCellIdentifier";
            
            let cell: UITableViewCell = UITableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: cellIdentifier)
            cell.selectionStyle = UITableViewCellSelectionStyle.none;
            if (indexPath as NSIndexPath).row < classArray.count {
                
                let dic = classArray[indexPath.row] as! JSON
                let mMonth = dic["mMonth"].stringValue
                let csnum = dic["csnum"].stringValue
                let StartDate = dic["StartDate"].stringValue
                let EndDate = dic["EndDate"].stringValue
                
                print("\(mMonth)月份、\(csnum)条、\(StartDate.components(separatedBy: " ").first!)-\(EndDate.components(separatedBy: " ").first!)")
                
            }
            
            return cell
            
        }else {
            let cellIdentifier = "OfficeGradeSendTableViewCellIdentifier";
            let cell: UITableViewCell = UITableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: cellIdentifier)
            cell.selectionStyle = UITableViewCellSelectionStyle.none;
            return cell
        }
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        HYLog("selected = \(indexPath.row + 1)")
    }
    
    func setupSwitchBtn() {
        
        if !self.tableView.subviews.contains(switchSegment) {
            
            switchSegment = UISegmentedControl.init(items: ["柱状图","折线图"])
            switchSegment.frame = CGRect(x: (screenW-150)/2, y: 5, width: 150, height: 30)
            switchSegment.selectedSegmentIndex = 0
            switchSegment.tintColor = UIColor.init(hexString: "#666666", alpha: 1.0)
            switchSegment.addTarget(self, action: #selector(OfficeLeaveViewController.refresh), for: UIControlEvents.valueChanged)
            self.tableView.addSubview(switchSegment)
        }
        
    }
    
    /*
    //MARK: - 设计柱状图
    
    func getBarChart() -> PDBarChart {
        
        
        let tempArr = NSMutableArray()
        var tempPointArr: [CGPoint]?
        var tempMouthArr: [String]?
        
        tempPointArr = [CGPoint]()
        tempMouthArr = [String]()
        
        for i in 0...classArray.count-1 {
            let tempNumber = (classArray[i] as! JSON)["csnum"].intValue
            let temgmMonth = (classArray[i] as! JSON)["mMonth"].intValue
            let tempPoint:CGPoint = CGPoint(x: (classArray[i] as! JSON)["mMonth"].intValue, y: (classArray[i] as! JSON)["csnum"].intValue)
            
            tempArr.add(tempNumber)
            tempPointArr?.append(tempPoint)
            tempMouthArr?.append("\(temgmMonth)月")
            
        }
        
        let dataItem: PDBarChartDataItem = PDBarChartDataItem()
        
        let m = tempArr.value(forKeyPath: "@max.intValue")! as! Int
        var ymax = CGFloat(0.0)
        var yinterval = CGFloat(0.0)
        
        if (m < 10) {
            ymax = CGFloat((m+1)*10)
            yinterval = 1.0
            
        }else if (m > 10 && m < 100) {
            ymax = CGFloat((m/10+1)*10)
            yinterval = 10.0
            
        }else if (m > 100 && m < 1000) {
            ymax = CGFloat((m/100+1)*10)
            yinterval = 100.0
            
        }else {
            ymax = CGFloat((m/1000+1)*10)
            yinterval = 1000.0
        }
        
        
        
        dataItem.xMax = CGFloat((tempMouthArr?.count)!)
        dataItem.xInterval = 1.0
        dataItem.yMax = ymax
        dataItem.yInterval = yinterval
        dataItem.barPointArray = tempPointArr
//            [CGPoint(x: 1.0, y: 95.0), CGPoint(x: 2.0, y: 25.0), CGPoint(x: 3.0, y: 30.0), CGPoint(x: 4.0, y:50.0), CGPoint(x: 5.0, y: 55.0), CGPoint(x: 6.0, y: 60.0), CGPoint(x: 7.0, y: 95.0), CGPoint(x: 8.0, y: 25.0), CGPoint(x: 9.0, y: 30.0), CGPoint(x: 10.0, y:50.0), CGPoint(x: 11.0, y: 55.0), CGPoint(x: 12.0, y: 60.0)]
        dataItem.xAxesDegreeTexts = tempMouthArr 
//            ["八月", "九月", "十月", "十一月", "十二月", "一月", "九月", "十月", "十一月", "十二月", "一月", "二月"]
        dataItem.yAxesDegreeTexts = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
        
        let frameW = self.view.frame.size.width
        let barChart: PDBarChart = PDBarChart(frame: CGRect(x: 0, y: 0, width: frameW, height: frameW), dataItem: dataItem)
        return barChart
    }
    //MARK: - 设计折线图
    func getLineChart() -> PDLineChart {
        let dataItem: PDLineChartDataItem = PDLineChartDataItem()
        dataItem.xMax = 7.0
        dataItem.xInterval = 1.0
        dataItem.yMax = 100.0
        dataItem.yInterval = 10.0
        dataItem.pointArray = [CGPoint(x: 1.0, y: 95.0), CGPoint(x: 2.0, y: 25.0), CGPoint(x: 3.0, y: 30.0), CGPoint(x: 4.0, y:50.0), CGPoint(x: 5.0, y: 55.0), CGPoint(x: 6.0, y: 60.0), CGPoint(x: 7.0, y: 90.0)]
        dataItem.xAxesDegreeTexts = ["周日", "一", "二", "三", "四", "五", "周六"]
        dataItem.yAxesDegreeTexts = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
        
        let frameW = self.view.frame.size.width
        let lineChart: PDLineChart = PDLineChart(frame: CGRect(x: 0, y: 100, width: frameW, height: frameW), dataItem: dataItem)
        return lineChart
    }
    
     */
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
